package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.message.NewsAutoScanConstants;
import com.heima.common.message.NewsUpOrDownConstants;
import com.heima.common.message.PublishArticleConstants;
import com.heima.common.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.校验参数
        if (dto == null || dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章或文章id不能为空");
        }
        Short enable = dto.getEnable();
        if(enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否发布
        if (!WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态 同步到App端
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,enable));

        if (WemediaConstants.WM_NEWS_UP.equals(enable)){
            //发送上架消息
            rabbitTemplate.convertAndSend(
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,
                    wmNews.getArticleId()
            );
            log.info("成功发送文章上架消息，消息内容：{}",wmNews.getArticleId());
        }else {
            //发送下架消息
            rabbitTemplate.convertAndSend(
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                    wmNews.getArticleId()
            );
            log.info("成功发送文章下架消息，消息内容：{}",wmNews.getArticleId());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据id删除文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //1.校验参数
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章id不能为空");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章状态
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
        && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章已上架发布，不能删除");
        }
        //4.去除素材与文章之间的关联关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 根据文章id查询文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.校验参数
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章id不能为空");
        }
        //2.执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.校验参数
        if (dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章或文章id不能为空");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //2.1检查文章状态，状态不能为9已发布状态
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        this.updateById(wmNews);
        //人工审核通过发送延时发布消息
        if (WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)) {
            //5.根据文章的具体发布时间  发送延时发布消息
            //5.1计算延迟时间
            long publishTime = wmNews.getPublishTime().getTime(); //获取发布时间
            long nowTime = System.currentTimeMillis(); //获取当前系统时间
            long remainTime = publishTime - nowTime; //延时发布时间
            //5.2发送消息，并设置延迟时间
            rabbitTemplate.convertAndSend(
                    PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                    PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                    wmNews.getId(),
                    new MessagePostProcessor() {
                        /**
                         * 消息的后置处理器，可以对消息属性进行设置
                         *
                         * @param message
                         * @return
                         * @throws AmqpException
                         */
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            //设置 x-delay 延迟时间
                            message.getMessageProperties().setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                            return message;
                        }
                    }
            );
            log.info("成功发送延时文章消息 文章id：{}  延时时间：{}", wmNews.getId(), remainTime);
        }
        //4.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1.校验参数
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章id不能为空");
        }
        //2.查询文章消息
        WmNews wmNews = getById(id);
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.查询作者
        WmUser wmUser = null;
        if (wmNews.getUserId() != null){
           wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        //4.返回结果
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVO);
        if (wmUser != null){
            wmNewsVO.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVO);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());

        if(StringUtils.isNotBlank(dto.getTitle())){
            //  concat(%,?,%)
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }

    /**
     * 查询所有自媒体文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1.校验参数
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"用户未登录");
        }
        //2.封装查询条件
        Page<WmNews> pageReq = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();
        //如果文章标题不为空则进行模糊查询
        String keyword = dto.getKeyword();
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like(WmNews::getTitle, keyword);
        }
        //如果有频道信息，按照频道id查询
        Integer channelId = dto.getChannelId();
        if (channelId != null){
            wrapper.eq(WmNews::getChannelId,channelId);
        }
        //如果有文章状态，按照状态信息查询
        Short status = dto.getStatus();
        if (status != null){
            wrapper.eq(WmNews::getStatus,status);
        }
        //如果开始时间，结束时间不为空，按照时间区间查询
        Date beginPubDate = dto.getBeginPubDate();
        Date endPubDate = dto.getEndPubDate();
        if (beginPubDate != null && endPubDate != null){
            wrapper.between(WmNews::getPublishTime,beginPubDate,endPubDate);
        }
        //按照登录用户id查询
        Integer id = user.getId();
        wrapper.eq(WmNews::getUserId,id);
        //按创建时间降序
        wrapper.orderByDesc(WmNews::getPublishTime);
        //3.执行查询
        IPage<WmNews> pageResult = page(pageReq, wrapper);
        //4.返回结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(), pageResult.getRecords());
        result.setHost(webSite);
        return result;
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //1.将dto封装成wmNews对象
        WmNews wmNews = getWmNews(dto);
        //2.保存或修改文章
        saveOrUpdateWmNews(wmNews);
        //2.1.如果文章为草稿状态则不用保存关联关系
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            return ResponseResult.okResult();
        }
        //3.保存文章 和 素材的关联关系
        //3.1从文章内容中抽取出所有的素材路径
        List<String> materialUrls = parseContentImages(wmNews.getContent());
        //3.2保存文章内容 所引用的素材 关联关系
        if (!CollectionUtils.isEmpty(materialUrls)) {
            saveRelativeInfo(materialUrls,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //3.3保存文章封面 所引用的素材 关联关系
        saveRelativeInfoForCover(dto,materialUrls,wmNews);

        //4.向mq发送消息 ，自动审核文章消息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送文章自动审核消息，当前待审核文章id:{}",wmNews.getId());

        return ResponseResult.okResult();
    }

    /**
     * 保存文章封面 所引用的素材 关联关系
     * 特殊情况 type=-1 代表自动生成封面
     * @param dto
     * @param materialUrls
     * @param wmNews
     */
    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> materialUrls, WmNews wmNews) {
        //前端传过来的封面列表
        List<String> images = dto.getImages();
        //特殊情况处理
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            int size = materialUrls == null ? 0 : materialUrls.size();
            if (size > 0 &&  size < 2){
                //单图
                images = materialUrls.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else if (size > 0){
                //多图
                images = materialUrls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            wmNews.setImages(imagesToString(images));
            this.updateById(wmNews);
        }
        //保存封面和素材的关联关系
        if (!CollectionUtils.isEmpty(images)) {
            //替换前缀路径
            images = images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    /**
     * 保存文章内容 所引用的素材 关联关系
     * @param materialUrls 素材路径
     * @param newsId 用户id
     * @param type 应用类型
     */
    private void saveRelativeInfo(List<String> materialUrls, Integer newsId, Short type) {
        //1.先根据素材路径列表 和 当前登录用户id 查询出素材id集合
        List<Integer> wmMaterials = wmMaterialMapper.selectRelationsIds(materialUrls, WmThreadLocalUtils.getUser().getId());
        /*List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materialUrls)
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                        .select(WmMaterial::getId)
        );*/
        //2.判断传入路径的数量和素材id的素材是否一致，不一致则代表素材丢失
        if (materialUrls.size() != wmMaterials.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材缺失，保存失败");
        }
        //3.将素材id文章id应用类型插入到关联表中
        wmNewsMaterialMapper.saveRelations(wmMaterials,newsId,type);
        /*for (WmMaterial wmMaterial : wmMaterials) {
            //批量保存关联关系
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(wmMaterial.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterialMapper.insert(wmNewsMaterial);
        }*/
    }

    /**
     * 从文章内容中抽取出所有的素材路径
     * 注意：去重，去前缀
     * @param content
     * @return 路径集合
     */
    private List<String> parseContentImages(String content) {
        List<Map> mapList = JSON.parseArray(content, Map.class);
        //获取流
        return mapList.stream()
                //过滤操作，过滤掉不是image的属性
                .filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))
                //获取map中的value的值 素材的完整路径
                .map(map -> String.valueOf(map.get("value")))
                //将完整路径的前缀替换掉
                .map(url -> url.replaceAll(webSite,""))
                //去重重复照片
                .distinct()
                //收集到list集合
                .collect(Collectors.toList());
    }

    private void saveOrUpdateWmNews(WmNews wmNews) {
        if (wmNews.getId() == null){
            //没有文章id，直接保存
            this.save(wmNews);
        }else {
            //有文章id，修改文章
            //先删除 此文章和素材的关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            //修改
            this.updateById(wmNews);
        }
    }

    private WmNews getWmNews(WmNewsDTO dto) {
        //校验参数
        if (StringUtils.isBlank(dto.getContent()) || StringUtils.isBlank(dto.getTitle())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章内容或标题不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"用户未登录");
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            wmNews.setType(null);
        }
        wmNews.setImages(imagesToString(dto.getImages()));
        //设置登录用户id
        wmNews.setUserId(user.getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);//默认上架
        return wmNews;
    }

    /**
     * 将封面集合 转为 字符串【webSite+url1,webSite+url2...】
     * @param images
     * @return
     */
    private String imagesToString(List<String> images) {
        if (CollectionUtils.isEmpty(images)){
            return null;
        }
        //获取流
        return images.stream()
                //映射 将每一个路径前缀替换
                .map(url -> url.replaceAll(webSite,""))
                //终止 将集合中的每个路径使用逗号拼接成一个字符串
                .collect(Collectors.joining(","));
    }
}
